<template>
  <view class="hs-tab-003">
    <scroll-view
      class="menu-scroll"
      scroll-x="true"
      :show-scrollbar="false"
      :scroll-left="scrollLeft"
      scroll-with-animation="true"
    >
      <view
        class="hs-tab-item"
        :class="activeIndex === index ? 'active' : ''"
        @click="changeTitle(index)"
        v-for="(item, index) in menuClassList"
        :key="index"
      >
        {{ item.name }}
      </view>
    </scroll-view>
  </view>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  getCurrentInstance,
} from "vue";

export default defineComponent({
  name: "hstab005",
  props: {},
  components: {},
  setup() {
    const data = reactive({
      activeIndex: 0,
      contentScrollW: 0,
      contentScrollLeft: 0,
      scrollLeft: 0,
      menuClassList: [
        { name: "推荐" },
        { name: "演唱会" },
        { name: "音乐节" },
        { name: "脱口秀" },
        { name: "Livehouse" },
        { name: "话剧音乐剧" },
        { name: "电影" },
        { name: "体育赛事" },
        { name: "展览" },
        { name: "音乐会" },
        { name: "曲艺杂谈" },
      ],
    });
    onMounted(() => {
      getScrollinfo();
    });

    // 获取滚动元素位置信息
    const { proxy } = getCurrentInstance();

    // 获取滚动元素信息
    const getScrollinfo = () => {
      const query = uni.createSelectorQuery().in(proxy);
      query
        .select(".menu-scroll")
        .boundingClientRect((ele) => {
          // 拿到 scroll-view 组件宽度

          data.contentScrollLeft = ele.left;
          data.contentScrollW = ele.width;
        })
        .exec(() => {
          getScrollItemInfo();
        });
    };
    // 获取每一项信息
    const getScrollItemInfo = () => {
      const query = uni.createSelectorQuery().in(proxy);
      query
        .selectAll(".hs-tab-item")
        .boundingClientRect((ele) => {
          let dataLen = ele.length;
          for (let i = 0; i < dataLen; i++) {
            //  scroll-view 子元素组件距离左边栏的距离
            data.menuClassList[i].left = ele[i].left - data.contentScrollLeft;
            //  scroll-view 子元素组件宽度
            data.menuClassList[i].width = ele[i].width;
          }
        })
        .exec();
    };

    // 点击tabs时
    const changeTitle = (index) => {
      data.activeIndex = index;
      // 设置选中tabs在中间显示
      data.scrollLeft =
        data.menuClassList[index].left -
        data.contentScrollW / 2 +
        data.menuClassList[index].width / 2;
    };
    return {
      changeTitle,
      ...toRefs(data),
    };
  },
});
</script>

<style scoped lang="less">
.hs-tab-003 {
  position: relative;

  .menu-scroll {
    white-space: nowrap;
    width: 100%;
    box-sizing: border-box;
    .hs-tab-item {
      display: inline-block;
      background: #fff;
      margin: 0 10rpx;
      padding: 8rpx 16rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      &.active {
        background: #000;
        color: #fff;
      }
    }
  }
}
</style>
